const fs = require('fs');
const publicARaster = require('./../../api/publicARaster');

let insertOrUpdate = (files,times) => `INSERT INTO draught_result values
${files.map(_ => {
    return `('${_.id}','${_.type}','${_.year}','${_.eday}','Z:\\\\draught_index_calculation_module\\\\result\\\\${_.filename}','${times}')`
}).join(',')}
on duplicate key update uploadtime='${times}';`.split('\n').join(' ');

let update = (task) => `UPDATE task set schedule='200' where id=${task.id};`;

/**
 * task 一个正常的 task 对象，定义和 /module/task.js 一致，但只需要 other 字段
 *
 * 该函数的 this 被绑定和 api/task 一致
 *
 * Z:\\draught_index_calculation_module/tmp/${logName}/
 * */
const dearProcess = function(R,task) {
    let info = JSON.parse(task.other);
    let times = new Date().getTime();
    let $this = this;
    let targetPath = `Z:\\draught_index_calculation_module\\tmp\\${info.dirName}`;
    // avi-2018-1.tif
    let files = ['avi','result','vhi','vswi'].map(_ => {
        return {
            id: `${_}${info.year}${info.eday}`,
            filename: `${_}-${info.year}-${info.eday}.tif`,
            type: _,
            year: info.year,
            eday: info.eday,
            rasterName: `${_}_${info.year}_${info.eday}`,
            path: `Z:\\draught_index_calculation_module\\result\\${_}-${info.year}-${info.eday}.tif`,
            srcPath: `${targetPath}\\${_}.tif`
        };
    });
    // info = {
    //     dirName: "15165165156164",
    //     year: 2018,
    //     eday: 1
    // }
    // 1.将文件剪切到指定文件中（覆盖也无所谓这里）
    files.forEach(_ => {
        fs.copyFileSync(_.srcPath,_.path);
    });
    // sql
    let sql = insertOrUpdate(files,times);
    // 2.发送请求
    publicARaster(files.map(_ => {
        return {
            workspace: 'draught',
            name: _.rasterName,
            path: _.path
        }
    }))
        .then(_ => {
            $this.db.query({
                sql
            },(err,ret) => {
                // 插入数据库 记录
                if (err) {
                    $this.defaultCallBack(R,err,ret);
                } else {
                    $this.db.query({
                        sql: update(task)
                    },(err,ret) => {
                        // 插入数据库 记录
                        if (err) {
                            $this.defaultCallBack(R,err,ret);
                        } else {
                            // 删除文件
                            files.forEach(_ => fs.unlinkSync(_.srcPath));
                            fs.rmdirSync(targetPath);
                            $this.defaultCallBack(R,null,'成功');
                        }
                    });
                }
            });
        })
        .catch($this.defaultCallBack.bind($this,R));
};

module.exports = function(db,R) {
    let { content : { param : { id } } } = R;
    let $this = this;
    if (id) {
        db.query({
            sql: `select * from task where id="${id}"`
        },(err,ret) => {
            if (err) {
                $this.defaultCallBack(R,err,ret);
            } else if (ret instanceof Array && ret.length == 1) {
                if (ret[0].schedule === 100) {
                    // 开始正常流程的处理
                    dearProcess.bind($this)(R,ret[0]);
                } else {
                    $this.defaultCallBack(R,"该流程不能发布",{});
                }
            } else {
                $this.defaultCallBack(R,"获取不到数据",ret);
            }
        });
    } else {
        this.defaultCallBack(R,"参数错误，参数应该包含字段 id");
    }
};